<template>
  <div class="content">
    <mHeader :project-name="projectName+'接口文档'"></mHeader>
    <!--接口目录-->
    <div class="menu scrollbar" @click="resetChecked">
      <el-input placeholder="输入关键字进行过滤" v-model="filterApiText" suffix-icon="el-icon-search"></el-input>
      <div class="opt">
        <el-button-group>
          <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="moduleDialog"></el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" @click.stop="delApi"></el-button>
        </el-button-group>
      </div>
      <!--接口树-->
      <el-tree :data="apiList" :props="defaultProps" node-key="id" :highlight-current="true"
               :expand-on-click-node="false" @node-click="handleTreeClick"
               default-expand-all :filter-node-method="filterNode" ref="apiTree">
      </el-tree>
    </div>
    <!--接口详情-->
    <div class="detial scrollbar">
      <div style="flex: 1">
        <!--接口名称-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-input placeholder="接口名称" v-model="api.name"></el-input>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="saveApi">保存</el-button>
            <el-button type="warning" @click="sendApi">发送</el-button>
            <el-tooltip placement="right">
              <div slot="content">
                接口服务IP：是指测试这个接口时填写的临时值，只保存在本地 <br>
                每个项目唯一 <br>
              </div>
              <el-button type="text" icon="el-icon-question"></el-button>
            </el-tooltip>
          </el-col>
        </el-row>
        <!--接口描述-->
        <div class="description">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 15}" v-model="api.description"
                    placeholder="接口描述">
          </el-input>
        </div>
        <!--请求url-->
        <el-row :gutter="20" style="padding-top:20px;">
          <el-col :span="3">
            <el-select v-model="api.reqType" placeholder="请求类型">
              <el-option label="GET" value="get"></el-option>
              <el-option label="POST" value="post"></el-option>
            </el-select>
          </el-col>
          <el-col :span="9">
            <el-input placeholder="接口服务IP+端口号" v-model="apiIp">
              <template slot="prepend">http://</template>
            </el-input>
          </el-col>
          <el-col :span="12">
            <el-input placeholder="接口地址" v-model="api.url">
              <el-tooltip slot="suffix" placement="top">
                <div slot="content">
                  示例：http://127.0.0.1:8080/superapi/login <br>
                  是一个完整的可访问路径，注意 "/"
                </div>
                <i class="el-input__icon el-icon-question"></i>
              </el-tooltip>
            </el-input>
          </el-col>
        </el-row>

        <br>
        <!--请求参数-->
        <div class="reqParams">
          <el-tabs value="reqParams" type="border-card" @tab-click="">
            <el-tab-pane label="请求参数" name="reqParams">
              <el-table :data="reqParamsData" size="mini" border style="width: 100%">
                <el-table-column label="参数名" width="180">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入参数名" v-model="scope.row.name"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="类型" width="130">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.type" placeholder="参数类型">
                      <el-option label="int" value="int"></el-option>
                      <el-option label="string" value="string"></el-option>
                      <el-option label="boolean" value="boolean"></el-option>
                      <el-option label="double" value="double"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="need" label="必须" width="60">
                  <template slot-scope="scope">
                    <el-switch v-model="scope.row.isNeed"></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="描述" width="160">
                  <template slot-scope="scope">
                    <el-input type="textarea" placeholder="请输入描述" v-model="scope.row.description" autosize></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="备注">
                  <template slot-scope="scope">
                    <el-input type="textarea" placeholder="备注" v-model="scope.row.remark" autosize></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="模拟参数值" width="180">
                  <template slot-scope="scope">
                    <el-input type="textarea" placeholder="请输入测试值" v-model="scope.row.mockValue" autosize></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="70" align="center">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" icon="el-icon-minus"
                               @click="delReqParam(scope.row.tid)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="addParams">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addReqParams">添加</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <br>
        <!--请求头-->
        <div class="reqHeader">
          <div style="position: absolute;right: 15px;top:0;z-index: 21">
            <el-button type="text" icon="el-icon-circle-plus" v-if="!reqHeaderStatus"
                       @click="reqHeaderStatus=!reqHeaderStatus"></el-button>
            <el-button type="text" icon="el-icon-remove" v-else="reqHeaderStatus"
                       @click="reqHeaderStatus=!reqHeaderStatus"></el-button>
          </div>
          <el-tabs value="reqHeader" type="border-card">
            <el-tab-pane label="请求头" name="reqHeader" v-show="reqHeaderStatus">
              <el-table :data="reqHeaderData" size="mini" border style="width: 100%">
                <el-table-column prop="key_" label="key" width="150">
                  <template slot-scope="scope">
                    <el-input placeholder="" v-model="scope.row.key_"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="value_" label="value">
                  <template slot-scope="scope">
                    <el-input placeholder="" v-model="scope.row.value_"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="描述" width="250">
                  <template slot-scope="scope">
                    <el-input type="textarea" autosize v-model="scope.row.description"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="70" align="center">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" icon="el-icon-minus"
                               @click="delReqHeader(scope.row.tid)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="addParams">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addReqHeader">添加</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <br>
        <!--响应参数-->
        <div class="reqParams respParams">
          <div style="position: absolute;right: 15px;top:0;z-index: 21">
            <el-button type="text" icon="el-icon-circle-plus" v-if="!respParamsStatus"
                       @click="respParamsStatus=!respParamsStatus"></el-button>
            <el-button type="text" icon="el-icon-remove" v-else="respParamsStatus"
                       @click="respParamsStatus=!respParamsStatus"></el-button>
          </div>
          <el-tabs value="reqHeader" type="border-card">
            <el-tab-pane label="响应参数" name="reqHeader" v-show="respParamsStatus">
              <el-table :data="respParamsData" size="mini" border style="width: 100%">
                <el-table-column label="参数名" width="180">
                  <template slot-scope="scope">
                    <el-input placeholder="请输入参数名" v-model="scope.row.name"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="描述" width="250">
                  <template slot-scope="scope">
                    <el-input type="textarea" placeholder="请输入描述" v-model="scope.row.description" autosize></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="备注">
                  <template slot-scope="scope">
                    <el-input type="textarea" placeholder="备注" v-model="scope.row.remark" autosize></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="70" align="center">
                  <template slot-scope="scope">
                    <el-button type="danger" size="mini" icon="el-icon-minus"
                               @click="delRespParam(scope.row.tid)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="addParams">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addRespParams">添加</el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
        <br>
        <!--响应tab-->
        <el-tabs value="body" type="border-card">
          <el-tab-pane label="响应结果" name="body">
            <div id="respJson"></div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!--添加模块弹窗-->
    <el-dialog title="新增模块" :visible.sync="addModuleDialog" :modal-append-to-body="false" :closeOnClickModal="false">
      <el-form>
        <el-form-item label="模块名称" label-width="120px">
          <el-input placeholder="请输入名称" v-model="moduleName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addModuleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveModule">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<style lang="scss">
  .content {
    .el-tree {
      border: none;
    }
    .detial {
      .description {
        margin-top: 20px;
      }
    }
    #respJson {
      font-size: 14px;
      padding: 0 15px;
    }
  }
</style>
<script>
  import mHeader from '../components/header.vue'
  import router from '../router'
  import http from '../api/http'
  import util from '../util'
  import store from '../util/store'
  import axios from 'axios'
  import qs from 'qs'
  import {server} from '../api/config'
  import '../util/jquery-1.11.1.min'
  import '../util/jquery.jsonview'
  import '../scss/jquery.jsonview.css'

  export default {
    data() {
      return {
        filterApiText: '', // 接口筛选输入
        apiList: [],
        api: {
          pid: '',
          name: '',
          description: '',
          reqType: '',
          url: '',
        },
        reqParamsData: [],
        reqHeaderData: [],
        respParamsData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        addModuleDialog: false,
        moduleName: '',
        respText: '',
        projectName: store.get('projectName'),
        reqHeaderStatus: true,
        respParamsStatus: true,
        apiIp: store.get('apiIp' + store.get('projectId')) || ''
      };
    },
    components: {
      mHeader
    },
    watch: {
      filterApiText(val) {
        this.$refs.apiTree.filter(val)
      }
    },
    mounted() {
      this.getApis()
    },
    methods: {
      getApis() {
        http.get('api/list', {id: store.get('projectId')}).then(response => {
          this.apiList = util.toTreeData(response.data)
        })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 选中接口
      handleTreeClick(obj) {
        if (obj.pid != 0) {
          this.api = obj
        } else {
          this.api = {}
        }
        this.reqParamsData = obj.reqParam ? JSON.parse(obj.reqParam) : []
        this.reqHeaderData = obj.reqHeader ? JSON.parse(obj.reqHeader) : []
        this.respParamsData = obj.respData ? JSON.parse(obj.respData) : []
        $('#respJson').html('')
      },
      // 删除接口
      delApi() {
        let chooseNode = this.$refs.apiTree.getCurrentNode()
        if (!chooseNode) {
          this.$message.error('请选择要删除项！')
          return
        }
        this.$confirm('确定删除当前选中项？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          http.get('api/del', {id: chooseNode.id}).then(response => {
            this.$message.success('操作成功')
            this.getApis()
          })
        }).catch(() => {
          this.$message('取消操作')
        })
      },
      // 重置左侧菜单选项
      resetChecked() {
        this.$refs.apiTree.setCurrentNode({})
        this.api = {}
      },
      // 保存接口详细信息
      saveApi() {
        this.api.reqParam = JSON.stringify(this.reqParamsData)
        this.api.reqHeader = JSON.stringify(this.reqHeaderData)
        this.api.respData = JSON.stringify(this.respParamsData)
        this.api.creater = store.get('username')
        http.post('api/put', {
          ...this.api,
          userId: store.get('userId')
        }).then(response => {
          this.getApis()
        })
        this.$message.success('操作成功')
      },
      // 删除请求头
      delReqHeader(tid) {
        let rhd = this.reqHeaderData
        for (let r in rhd) {
          if (rhd[r].tid == tid) {
            rhd.splice(r, 1)
          }
        }
      },
      // 删除请求参数
      delReqParam(tid) {
        let rpd = this.reqParamsData
        for (let r in rpd) {
          if (rpd[r].tid == tid) {
            rpd.splice(r, 1)
          }
        }
      },
      // 删除响应参数
      delRespParam(tid) {
        let rpd = this.respParamsData
        for (let r in rpd) {
          if (rpd[r].tid == tid) {
            rpd.splice(r, 1)
          }
        }
      },
      // 添加请求参数
      addReqParams() {
        let rpd = this.reqParamsData
        let obj = {
          tid: rpd.length,
          name: '',
          type: '',
          isNeed: false,
          description: ''
        }
        rpd.push(obj)
      },
      // 添加请求头
      addReqHeader() {
        let rhd = this.reqHeaderData
        let obj = {
          tid: rhd.length,
          key_: '',
          value_: '',
          description: ''
        }
        rhd.push(obj)
      },
      // 添加响应参数
      addRespParams() {
        let rhd = this.respParamsData
        let obj = {
          tid: rhd.length,
          name: '',
          description: '',
          remark: ''
        }
        rhd.push(obj)
      },
      // 添加模块弹窗
      moduleDialog() {
        this.addModuleDialog = true
        if (this.api.pid != 0) {
          this.isAddApi = true
        }
      },
      // 保存模块
      saveModule() {
        let chooseKey = this.$refs.apiTree.getCurrentKey()
        if (chooseKey) {
          this.api.pid = chooseKey
        }
        this.api.projectId = store.get('projectId')
        this.api.name = this.moduleName
        http.post('api/put', {
          ...this.api,
          userId: store.get('userId')
        }).then(response => {
          this.addModuleDialog = false
          this.api = {}
          this.moduleName = ''
          this.getApis()
        })
      },
      // 发送当前接口请求
      sendApi() {
        // TODO 复制url
        store.set('apiIp' + store.get('projectId'), this.apiIp)
        let reqType = this.api.reqType
        let url = 'http://' + this.apiIp + this.api.url
        let params = util.handleReqParams(this.reqParamsData)
        let headers = util.handleReqHeaders(this.reqHeaderData)
        if (reqType == 'get') {
          axios({
            method: 'get',
            url: url,
            params: params,
            headers: headers
          }).then(response => {
            $("#respJson").jsonViewer(response.data)
          })
        } else if (reqType == 'post') {
          axios({
            method: 'post',
            url: url,
            data: qs.stringify(params),
            headers: headers
          }).then(response => {
            $("#respJson").jsonViewer(response.data)
          })
        }
      }
    }
  };
</script>
